﻿using System;
using System.Collections;
using System.Linq;
using System.Windows;
using System.Windows.Controls;

using Microsoft.SharePoint.Client;

using DevExpress.Utils;
using DevExpress.Xpf.Data;
using DevExpress.Xpf.Grid;

using SBPweb.RIA.Client.Common.Collections;
using SBPweb.RIA.Client.Contracts.Base;
using SBPweb.RIA.Client.Controls.Extensions;

using SBPweb.PROvibe.Client.Library.Controls;

using SBPweb.PROvibe.Client.Modules.MOSS14Connector.Model.Lists;

namespace SBPweb.PROvibe.Client.Modules.MOSS14Connector.Controls
{

    public partial class MainWindow : WindowBase
    {

        #region Fields

        #endregion

        #region Construcor logic

        public MainWindow()
            : base("WindowsRootPanel")
        {
            InitializeComponent();
        }

        #endregion

        #region Dependencies

        public static readonly DependencyProperty ListNameProperty = DependencyProperty.Register("ListName", typeof(string), typeof(MainWindow), null);

        #endregion

        #region Properties

        internal Services.Moss14ConnectorService Service
        {
            get;
            private set;
        }

        internal ClientContext MossContext
        {
            get
            {
                return Service.MossContext;
            }
        }
        
        #endregion

        #region Event handlers

        protected override void InitializeHandlers()
        {
            base.InitializeHandlers();

            Service = ClientContext.ContentContextController.GetService<Services.Moss14ConnectorService>();
            if (Service.IsAvailable && Service.IsInitialized)
            {
                Service_Initialized(this, EventArgs.Empty);
            }
            else
            {
                Service.Initialized += new EventHandler(Service_Initialized);
            }
        }
        
        protected override void OnLoaded(object sender, RoutedEventArgs e)
        {
            base.OnLoaded(sender, e);
        }

        private void Service_Initialized(object sender, EventArgs e)
        {
            //fetchedListPropertyCount = 0;

            lgList.InitializeContext(MossContext);

            cmbxLists.ItemsSource = MossContext.Web.Lists;
            cmbxLists.SelectedValue = cmbxLists.Items.Cast<List>().FirstOrDefault(x => x.Title == lgList.ListName);
        }

        private void cmbxLists_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            List list = e.AddedItems[0] as List;
            if (lgList.ListName != list.Title)
            {
                lgList.ListName = list.Title;
                lgList.FetchList();
            }
        }

        //public void FetchList()
        //{
        //    list = lists.GetByTitle(ListName);

        //    gcItems.ShowLoadingPanel = true;

        //    MossContext.Load(list.Fields);
        //    MossContext.Load(list.Views);
        //    MossContext.ExecuteQueryAsync(onListSucceeded, onListFailed);
        //}

        //private void onListSucceeded(object sender, ClientRequestSucceededEventArgs args)
        //{
        //    if (fetchedListPropertyCount++ < 1)
        //    {
        //        return;
        //    }
        //    view = list.Views.FindDefaultView();

        //    if (view == null)
        //    {
        //        return;
        //    }

        //    MossContext.Load(view, x => x.ViewFields);
        //    MossContext.ExecuteQueryAsync(onViewSucceeded, onViewFailed);
        //}

        //private void onListFailed(object sender, ClientRequestFailedEventArgs args)
        //{
        //    this.Dispatcher.BeginInvoke(() => gcItems.ShowLoadingPanel = false);
        //    throw args.Exception;
        //}
        
        //private void onViewSucceeded(object sender, ClientRequestSucceededEventArgs args)
        //{
        //    this.Dispatcher.BeginInvoke(() => PopulateColumns());
        //}

        //private void onViewFailed(object sender, ClientRequestFailedEventArgs args)
        //{
        //    this.Dispatcher.BeginInvoke(() => gcItems.ShowLoadingPanel = false);
        //    throw args.Exception;
        //}

        //protected virtual void PopulateColumns()
        //{
        //    gcItems.Columns.Clear();
        //    //int i = 0;
        //    foreach (var f in list.Fields)
        //    {
        //        gcItems.Columns.Add(new GridColumn()
        //        {
        //            //Name = string.Format("gc_{0}_{1}", i++, f.StaticName),
        //            FieldName = f.StaticName,
        //            Header = f.StaticName,
        //            ReadOnly = f.ReadOnlyField,
        //            AllowSorting = f.Sortable ? DefaultBoolean.True : DefaultBoolean.False,
        //            AllowColumnFiltering = f.Filterable ? DefaultBoolean.True : DefaultBoolean.False,
        //            BestFitMode = DevExpress.Xpf.Core.BestFitMode.Smart,
        //            AllowBestFit = DefaultBoolean.True,
        //            Visible = false
        //        });
        //    }
        //    foreach (var fn in view.ViewFields)
        //    {
        //        GridColumn gc = gcItems.Columns[fn];
        //        if (gc != null)
        //        {
        //            gc.Visible = true;
        //        }
        //    }

        //    ListItemValuesFactory fac = new ListItemValuesFactory("ListName", list.Fields);
        //    IList ols = fac.CreateListInstance();
        //    //ObservableList<ListItemValues> ols = fac.CreateListInstance();
        //    gcItems.DataSource = ols;

        //    gcItems.ShowLoadingPanel = false;

            
        //    items = list.GetItems(new CamlQuery() { ViewXml = view.ViewQuery });

        //    worker = new ListItemValuesListWorker(fac, items, ols);

        //    MossContext.Load(items);
        //    MossContext.ExecuteQueryAsync(onItemsSucceeded, onItemsFailed);

        //    //BackgroundWorker bw = new BackgroundWorker();
        //    //bw.DoWork += new DoWorkEventHandler(bw_DoWork);
        //    //bw.RunWorkerAsync();
        //}
        
        //private void onItemsSucceeded(object sender, ClientRequestSucceededEventArgs args)
        //{
        //    this.Dispatcher.BeginInvoke(() => PopulateRows());
        //}

        //private void onItemsFailed(object sender, ClientRequestFailedEventArgs args)
        //{
        //    this.Dispatcher.BeginInvoke(() => gcItems.ShowLoadingPanel = false);
        //    throw args.Exception;
        //}
        
        //protected virtual void PopulateRows()
        //{
        //    foreach (var item in worker.SourceList)
        //    {
        //        worker.TargetList.Add(worker.Factory.CreateItemInstance(item));
        //    }
        //}

        #endregion

    }
    
    //public class ListItemValueConverter : IValueConverter
    //{

    //    public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    //    {
    //        RowData rd = value as RowData;
    //        ListItemValues item = rd.Row as ListItemValues;
    //        string fieldName = parameter as string;
    //        return item.GetValue(fieldName);
    //    }

    //    public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    //    {
    //        throw new NotImplementedException();
    //    }

    //}

}